package xyz.chaobei.util;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import xyz.chaobei.enums.ResultCodeEnum;

/**
 * Copyright (C), 2015-2020
 * FileName: JsonUtil
 * Author:   MRC
 * Date:     2020/1/22 22:39
 * Description: json 返回单例模式
 * History:
 */
public class JsonUtil {

    private static final JSONObject object = new JSONObject();

    public static synchronized JSONObject getSuccess() {

        ResultCodeEnum normal = ResultCodeEnum.NORMAL;
        return result(normal.getCode(), null, normal.getDesc());
    }

    public static synchronized JSONObject getSuccess(Object data) {

        ResultCodeEnum normal = ResultCodeEnum.NORMAL;
        return result(normal.getCode(), data, normal.getDesc());
    }

    /**
     * 返回成功分页信息
     *
     * @return
     */
    public static synchronized JSONObject getSuccessPage(Page page) {

        ResultCodeEnum normal = ResultCodeEnum.NORMAL;
        object.clear();
        object.put("code" , 0);
        object.put("count" , page.getTotal());
        object.put("msg" , normal.getDesc());
        object.put("data" , page.getRecords());

        return object;
    }

    /**
     * 通过一个布尔值控制返回
     *
     * @param is
     * @return
     */
    public static synchronized JSONObject getResult(boolean is) {
        if (is) {
            return result(ResultCodeEnum.NORMAL.getCode(), null, "操作成功");
        }
        return result(ResultCodeEnum.ERROR.getCode(), null, "操作失败");
    }

    public static synchronized JSONObject getSuccessMsg(String msg) {

        ResultCodeEnum normal = ResultCodeEnum.NORMAL;
        return result(normal.getCode(), null, msg);
    }

    public static synchronized JSONObject getFailMsg(String msg) {

        ResultCodeEnum error = ResultCodeEnum.ERROR;
        return result(error.getCode(), null, msg);
    }


    /**
     * @return com.alibaba.fastjson.JSONObject
     * @Author MRC
     * @Description 返回
     * @Date 22:40 2020/1/22
     * @Param []
     **/
    public static JSONObject result(Integer code, Object data, String msg) {

        object.clear();

        object.put("code" , code);
        object.put("data" , data);
        object.put("msg" , msg);

        return object;
    }

}